<template>
  <div>
    <div class="flex justify-between items-center px-20px pt-20px">
      <p class="">我发布的产品</p>
      <el-button
        icon="el-icon-plus"
        type="primary"
        plain
        size="small"
        @click="onIssue"
      >发布产品</el-button>
    </div>
    <el-divider></el-divider>
    <el-form
      :inline="true"
      :model="searchForm"
      class="p-10px px-30px"
    >
      <el-form-item label="产品名称">
        <el-input
          v-model="searchForm.productName"
          clearable
          placeholder="请输入产品名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="small"
          @click="search"
        >查询</el-button>
      </el-form-item>
    </el-form>
    <div class="card">
      <el-tabs
        v-model="activeName"
        @tab-click="tabClick"
        type="border-card"
        class="mx-10px mb-30px"
      >
        <el-tab-pane
          :label="item.dictLabel"
          :name="item.dictValue"
          v-for="(item, index) in productApplyStatus"
          :key="index"
        >
          <el-table
            v-loading="tableLoading"
            :data="tableList"
            style="width: 100%"
          >
            <el-table-column
              prop="productName"
              label="产品名称"
            ></el-table-column>
            <el-table-column
              prop="productTypeParentName"
              label="所属品类"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="productTypeName"
              label="二级类型"
              align="center"
            ></el-table-column>

            <el-table-column label="产品状态">
              <template slot-scope="scope">
                <span
                  v-if="scope.row.listStatus == 0"
                  class="text-[#e6a23c]"
                >未上架</span>
                <span
                  v-if="scope.row.listStatus == 1"
                  class="text-[#67c23a]"
                >已上架</span>
                <span
                  v-if="scope.row.listStatus == 2"
                  class="text-[#f56c6c]"
                >下架</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="200px"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="(scope.row.auditStatus == -1 && scope.row.listStatus == 0) || (scope.row.auditStatus == 2 && scope.row.listStatus == 0)"
                  type="text"
                  class="ml-10px"
                  @click="btnClick(scope.row, scope.$index, 'edit')"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="scope.row.auditStatus == 0"
                  type="text"
                  class="ml-10px"
                  @click="btnClick(scope.row, scope.$index, 'revoke')"
                >
                  撤回
                </el-button>
                <el-button
                  v-if="(scope.row.listStatus == 0 && scope.row.auditStatus == -1) || (scope.row.listStatus == 2 && scope.row.auditStatus == -1)"
                  type="text"
                  class="ml-10px"
                  @click="btnClick(scope.row, scope.$index, 'ground')"
                >
                  上架
                </el-button>
                <el-button
                  v-if="scope.row.listStatus == 1"
                  type="text"
                  class="ml-10px"
                  @click="btnClick(scope.row,scope.$index, 'ground')"
                >下架
                </el-button>
                <el-button
                  type="text"
                  class="ml-10px"
                  v-if="scope.row.listStatus == 0 && scope.row.auditStatus == -1"
                  @click="btnClick(scope.row, scope.$index, 'delete')"
                >
                  删除
                </el-button>
                <el-button
                  type="text"
                  class="ml-10px"
                  @click="btnClick(scope.row, scope.$index, 'view')"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="flex justify-end mt-15px">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageData.currentPage"
              :page-sizes="[10, 20, 30, 40, 50]"
              :page-size="pageData.pageSize"
              layout="total, prev, pager, next"
              :total="pageData.totalPage"
            >
            </el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 产品上架 -->
    <el-dialog
      :title="type == 'view'?'产品详情':'发布产品'"
      width="1000px"
      :visible="issueDialogVisible"
      @close="handleDialogClose"
    >
      <el-form
        :rules="serviceRules"
        ref="serviceForm"
        :model="serviceData"
        size="medium"
        label-width="120px"
        :disabled="type == 'view'"
      >
        <el-form-item
          label="产品名称"
          prop="productName"
        >
          <el-input
            placeholder="请输入包含核心参数的产品名称，如：1.8mm 5052 铝合金板"
            v-model="serviceData.productName"
          ></el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="所属品类"
              prop="productTypePid"
            >
              <el-select
                v-model="serviceData.productTypePid"
                placeholder="请选择所属品类"
                style="width: 100%;"
                @change="handleFirstCategoryChange"
              >
                <el-option
                  v-for="item in types"
                  :key="item.productTypeId"
                  :label="item.productTypeName"
                  :value="item.productTypeId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="二级类型"
              prop="productTypeId"
            >
              <el-select
                v-model="serviceData.productTypeId"
                placeholder="请选择二级类型"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in secondLevelCategories"
                  :key="item.productTypeId"
                  :label="item.productTypeName"
                  :value="item.productTypeId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          label="基础属性"
          prop="basicAttributes"
        >
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入基础属性，如：型号 G-2024，40Cr 合金材质（锻造 + 热处理工艺），外径 80mm× 内径 30mm× 厚度 15mm，重量 0.8kg 产能 / 供应量、单价（可填区间或 “面议”）"
            v-model="serviceData.basicAttributes"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="性能参数"
          prop="performanceParameters"
        >
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入性能参数，如：模数 4，齿数 20，精度等级 6 级，硬度 HRC45-50，传动效率≥98%，工作温度 - 20℃~120℃"
            v-model="serviceData.performanceParameters"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="产能效率"
          prop="productionCapacity"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入产能效率信息，如：单件加工周期 4 小时，使用寿命≥8000 小时"
            v-model="serviceData.productionCapacity"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="质量标准"
          prop="qualityStandard"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入质量标准信息，如：符合 GB/T 10095-2018 标准，出厂合格率 99.8%，质保 1 年"
            v-model="serviceData.qualityStandard"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="适配场景"
          prop="adaptationScenario"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入适配场景信息，如：适用于汽车变速箱、工业减速机、新能源设备，适配转速≤3000r/min"
            v-model="serviceData.adaptationScenario"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="交货周期"
          prop="deliveryCycle"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入交货周期"
            v-model="serviceData.deliveryCycle"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="交货地点"
          prop="deliveryPlace"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入交货地点，如：广西主要物流节点：南宁国际铁路港、钦州港、柳州物流园等"
            v-model="serviceData.deliveryPlace"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="产品优势"
          prop="productAdvantages"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入产品优势信息，如：（突出广西特色：如 “水电铝生产，绿色低碳”“靠近东盟市场，出口便捷”）"
            v-model="serviceData.productAdvantages"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="产品说明"
          prop="productComment"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入产品说明"
            v-model="serviceData.productComment"
          ></el-input>
        </el-form-item>

        <!-- 产品主图上传 -->
        <el-form-item
          label="产品主图"
          prop="productImg"
        >
          <el-upload
            ref="imageUpload"
            class="avatar-uploader"
            :action="uploadAction"
            :data="uploadData"
            :headers="uploadHeaders"
            :auto-upload="true"
            :show-file-list="true"
            :on-success="handleUploadSuccess"
            :on-exceed="handleExceed"
            :limit="1"
            list-type="picture-card"
            :on-remove="handleRemove"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div
            class="el-upload__tip"
            slot="tip"
          >只能上传1张图片，建议尺寸800*800像素</div>
        </el-form-item>

        <!-- 附件上传 -->
        <el-form-item
          label="附件"
          prop="attachments"
        >
          <el-upload
            ref="attachmentUpload"
            class="upload-demo"
            :action="uploadAction"
            :data="uploadData"
            :headers="uploadHeaders"
            :auto-upload="true"
            :on-success="handleAttachmentSuccess"
            :on-remove="handleAttachmentRemove"
            :on-preview="handleAttachmentPreview"
            :file-list="attachmentList"
            multiple
          >
            <el-button
              size="small"
              type="primary"
            >点击上传</el-button>
            <div
              slot="tip"
              class="el-upload__tip"
            >可上传产品图片、检测报告、专利证书等文件</div>
          </el-upload>
        </el-form-item>

        <el-form-item v-if="type == 'edit'">
          <div class="submit_box">
            <el-button
              type="primary"
              plain
              @click="saveOrApplyProduct(false)"
              style="width: 120px"
              v-loading="saveBtnLoading"
            >
              暂时保存
            </el-button>
            <el-button
              type="primary"
              v-loading="applyBtnLoading"
              style="width: 120px;margin-left: 20px;"
              @click="saveOrApplyProduct(true)"
            >申请上架
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  productTypeList,
  getProductOwePage,
  productGround,
  productRevoke,
  productDelete,
  saveProduct,
  getProductDetail,
  updateProductPrice,
  productTypeChildrenList,
} from "@/api/home";
import { mapGetters } from "vuex";
import { getToken } from "@/utils/auth";

export default {
  data() {
    return {
      isHaveInfo: true,
      tableLoading: false,
      listData: [],
      activeName: "all",
      productApplyStatus: [
        { dictLabel: "全部", dictValue: "all" },
        { dictLabel: "待审核", dictValue: "0" },
        { dictLabel: "审核通过", dictValue: "1" },
        { dictLabel: "退回修改", dictValue: "2" },
        { dictLabel: "审核不通过", dictValue: "3" },
        { dictLabel: "已上架", dictValue: "4" },
        { dictLabel: "已下架", dictValue: "5" },
      ],
      pageData: {
        currentPage: 1,
        pageSize: 5,
        totalPage: 0,
      },
      tableList: [],
      searchForm: {
        productName: "",
      },
      serviceData: {
        productImg: "",
        basicAttributes: "",
        performanceParameters: "",
        productionCapacity: "",
        qualityStandard: "",
        adaptationScenario: "",
        deliveryCycle: "",
        deliveryPlace: "",
        productAdvantages: "",
        attachments: "",
        productComment: "",
      },
      serviceRules: {
        productName: [
          { required: true, message: "请输入产品名称", trigger: "blur" },
        ],
        productTypePid: [
          { required: true, message: "请选择所属品类", trigger: "change" },
        ],
        productImg: [
          { required: true, message: "请上传产品主图", trigger: "change" },
        ],
      },
      issueDialogVisible: false,
      applyBtnLoading: false,
      saveBtnLoading: false,
      uploadAction: process.env.VUE_APP_BASE_API + "api/private/file/v1/upload",
      uploadData: {
        open: 1,
      },
      uploadHeaders: {
        Authorization: "Bearer " + getToken(),
      },
      types: [],
      fileList: [], // 用于图片回显
      attachmentList: [], // 用于附件回显
      type: "edit",
      // 二级分类相关
      secondLevelCategories: [],
    };
  },
  computed: {
    ...mapGetters("dicts", ["cityDict", "getDictByParamsKey"]),
    ...mapGetters("user", ["userInfo"]),
    industrys() {
      return this.getDictByParamsKey({ parentId: 1 });
    },
  },
  mounted() {
    this.getTableList();
    this.getData();
  },
  methods: {
    getData() {
      productTypeList().then((res) => {
        this.types = res.data;
      });
    },
    // 处理一级分类变化
    handleFirstCategoryChange(value) {
      // 重置二级分类
      this.serviceData.productTypeId = "";
      this.secondLevelCategories = [];

      if (value && value !== "") {
        // 获取二级分类数据
        productTypeChildrenList({ parentId: value }).then((res) => {
          this.secondLevelCategories = res.data || [];
        });
      }
    },

    // 处理附件上传成功
    handleAttachmentSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 保存附件ID列表
        const attachmentIds = fileList
          .map((f) => f.response?.data?.fileId || f.fileId)
          .filter((id) => id);
        this.$set(this.serviceData, "attachments", attachmentIds.join(","));
        this.attachmentList = fileList;
      }
    },

    // 处理附件删除
    handleAttachmentRemove(file, fileList) {
      const attachmentIds = fileList
        .map((f) => f.response?.data?.fileId || f.fileId)
        .filter((id) => id);
      this.$set(this.serviceData, "attachments", attachmentIds.join(","));
      this.attachmentList = fileList;
    },

    // 处理附件预览（点击下载）
    handleAttachmentPreview(file) {
      // 获取文件的完整URL
      let fileUrl = "";
      
      // 如果文件有url属性，直接使用
      if (file.url) {
        fileUrl = file.url;
      } 
      // 如果有fileId，构造URL
      else if (file.fileId) {
        fileUrl = `${process.env.VUE_APP_BASE_API}api/public/file/v1/public/get/${file.fileId}`;
      }
      // 如果有response且有fileId，构造URL
      else if (file.response && file.response.data && file.response.data.fileId) {
        fileUrl = `${process.env.VUE_APP_BASE_API}api/public/file/v1/public/get/${file.response.data.fileId}`;
      }
      
      // 在新窗口中打开文件URL实现下载
      if (fileUrl) {
        window.open(fileUrl, '_blank');
      } else {
        this.$message.warning("无法获取文件地址");
      }
    },

    // 产品主图上传成功处理
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 保存文件ID到productImg
        this.$set(this.serviceData, "productImg", response.data.fileId);
        // 更新文件列表
        this.fileList = fileList.slice(-1); // 只保留最后一个文件
      }
    },

    // 删除图片处理
    handleRemove(file, fileList) {
      this.$set(this.serviceData, "productImg", "");
      this.fileList = fileList;
    },

    // 超出限制处理
    handleExceed(files, fileList) {
      this.$message.warning("只能上传1张图片");
    },

    tabClick(val) {
      if (val.name === "all") {
        this.getTableList();
      } else if (val.name === "0") {
        this.getTableList(0);
      } else if (val.name === "1") {
        this.getTableList(1);
      } else if (val.name === "2") {
        this.getTableList(2);
      } else if (val.name === "3") {
        this.getTableList(3);
      } else if (val.name === "4") {
        this.getTableList("", 1);
      } else if (val.name === "5") {
        this.getTableList("", 2);
      }
    },
    handleSizeChange(val) {
      this.$set(this.pageData, "pageSize", val);
      this.getTableList();
    },
    handleCurrentChange(val) {
      this.$set(this.pageData, "currentPage", val);
      this.getTableList();
    },
    search() {
      this.$set(this.pageData, "currentPage", 1);
      this.getTableList();
    },
    getTableList(auditStatus = "", listStatus = "") {
      this.tableLoading = true;
      getProductOwePage({
        pageNo: this.pageData.currentPage,
        pageNum: this.pageData.pageSize,
        auditStatus,
        listStatus,
        ...this.searchForm,
      })
        .then((res) => {
          if (res.code === 200) {
            this.tableList = [...res.rows];
            this.pageData.totalPage = res.total;
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    btnClick(row, index, type) {
      let self = this;
      switch (type) {
        case "ground":
          let listStatus = 0;
          self.tableLoading = true;
          if (row.listStatus == 0 || row.listStatus == 2) {
            // 未上架、下架进行上架操作
            listStatus = 1;
            self.handleGroundOperation(row, listStatus);
          } else if (row.listStatus == 1) {
            // 上架进行下架操作
            listStatus = 2;
            // 上架进行下架操作，添加确认提示
            self
              .$confirm(
                "下架后需要通过下一批次产品审核才能重新上架，确认是否下架？（本批需要调整的产品下架后优先审核）",
                "温馨提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              )
              .then(() => {
                listStatus = 2;
                self.handleGroundOperation(row, listStatus);
              })
              .catch(() => {
                self.tableLoading = false;
              });
          }
          break;
        case "edit":
          this.getDetail(row);
          this.type = "edit";
          break;
        case "revoke":
          this.$confirm("是否撤回此条数据?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              productRevoke({ productId: row.productId })
                .then((res) => {
                  if (res.code === 200) {
                    self.$message.success("操作成功!");
                    self.getTableList();
                  } else {
                    self.$message.error(res.msg);
                  }
                })
                .finally(() => {
                  self.tableLoading = false;
                });
            })
            .catch(() => {});
          break;
        case "delete":
          this.$confirm("是否删除此条数据?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              productDelete({ productId: row.productId })
                .then((res) => {
                  if (res.code === 200) {
                    self.$message.success("操作成功!");
                    self.getTableList();
                  } else {
                    self.$message.error(res.msg);
                  }
                })
                .finally(() => {
                  self.tableLoading = false;
                });
            })
            .catch(() => {});
          break;
        case "view":
          this.getDetail(row);
          this.type = "view";
          break;
        default:
          break;
      }
    },
    getDetail(row) {
      getProductDetail({ productId: row.productId })
        .then((res) => {
          this.serviceData = res.data;
          
          // 处理二级分类数据
          if (res.data.productTypePid) {
            // 先获取二级分类数据
            productTypeChildrenList({ parentId: res.data.productTypePid }).then((response) => {
              this.secondLevelCategories = response.data || [];
              
              // 使用 $nextTick 确保 DOM 更新后再设置 productTypeId
              this.$nextTick(() => {
                this.serviceData.productTypeId = res.data.productTypeId;
              });
            });
          }

          // 设置图片回显
          this.setImagePreview(res.data.productImg);

          // 设置附件回显
          this.setAttachmentPreview(res.data.attachments);

          this.issueDialogVisible = true;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 设置附件预览
    setAttachmentPreview(attachmentIds) {
      if (attachmentIds) {
        this.attachmentList = [];
        const ids = attachmentIds.split(",");
        ids.forEach((id) => {
          if (id) {
            this.attachmentList.push({
              name: id,
              url: `${process.env.VUE_APP_BASE_API}api/public/file/v1/public/get/${id}`,
              fileId: id,
            });
          }
        });
        this.$set(this.serviceData, "attachments", attachmentIds);
      } else {
        this.attachmentList = [];
        this.$set(this.serviceData, "attachments", "");
      }
    },
    // 设置图片预览
    setImagePreview(fileId) {
      if (fileId) {
        // 清空之前的文件列表
        this.fileList = [];
        // 添加新文件到文件列表
        this.fileList.push({
          name: fileId,
          url: `${process.env.VUE_APP_BASE_API}api/public/file/v1/public/get/${fileId}`,
        });
        // 更新表单数据
        this.$set(this.serviceData, "productImg", fileId);
      } else {
        this.fileList = [];
        this.$set(this.serviceData, "productImg", "");
      }
    },
    // 新增处理上下架操作的方法
    handleGroundOperation(row, listStatus) {
      this.tableLoading = true;
      productGround({
        listStatus,
        productId: row.productId,
      })
        .then((res) => {
          if (res.code === 200) {
            this.$message.success(listStatus === 1 ? "上架成功!" : "下架成功!");
            this.getTableList();
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    onIssue() {
      if (this.userInfo.companyId) {
        // 重置表单数据
        this.$set(this, "serviceData", {
          productName: "",
          productTypePid: "",
          productTypeId: "",
          productImg: "",
          basicAttributes: "",
          performanceParameters: "",
          productionCapacity: "",
          qualityStandard: "",
          adaptationScenario: "",
          deliveryCycle: "",
          deliveryPlace: "",
          productAdvantages: "",
          attachments: "",
          productComment: "",
        });

        // 清空文件列表
        this.fileList = [];
        this.attachmentList = [];
        this.secondLevelCategories = [];
        // 清空上传组件
        if (this.$refs.imageUpload) {
          this.$refs.imageUpload.clearFiles();
        }
        if (this.$refs.attachmentUpload) {
          this.$refs.attachmentUpload.clearFiles();
        }
        this.type = "edit";
        this.issueDialogVisible = true;
      } else {
        //企业未绑定
        this.$router.go(0);
      }
    },
    // 对话框关闭时的处理
    handleDialogClose() {
      this.issueDialogVisible = false;
      this.$refs.serviceForm.resetFields();
      // 清空上传的文件
      this.$set(this.serviceData, "productImg", "");
      this.$set(this.serviceData, "attachments", "");
      this.fileList = [];
      this.attachmentList = [];
      this.secondLevelCategories = [];
      if (this.$refs.imageUpload) {
        this.$refs.imageUpload.clearFiles();
      }
      if (this.$refs.attachmentUpload) {
        this.$refs.attachmentUpload.clearFiles();
      }
    },
    // 产品暂存或者上架
    saveOrApplyProduct(applyForLaunch) {
      let self = this;
      self.$refs["serviceForm"].validate((valid) => {
        if (valid) {
          const data = { ...this.serviceData };
          data.applyForLaunch = applyForLaunch;

          saveProduct(data).then((res) => {
            if (res.code == 200) {
              this.$message.success(
                `${applyForLaunch ? "产品信息提交" : "产品信息暂存"}成功！`
              );
              this.productId = res.data.productId;
              this.issueDialogVisible = false;
              this.getTableList();
            }
          });
        }
      });
    },
  },
};
</script>

<style scoped>
p {
  margin: 0;
  padding: 0;
}

:deep(.el-divider--horizontal) {
  margin: 12px 0;
}

:deep(.el-menu--horizontal > .el-menu-item.is-active) {
  border-bottom-color: #d32521;
}

:deep(.el-table thead) {
  color: #000;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-demo {
  width: 100%;
}

/* 为附件列表中的文件名添加样式，使其看起来更像可点击的链接 */
:deep(.el-upload-list__item-name) {
  color: #409eff;
  cursor: pointer;
}

:deep(.el-upload-list__item-name:hover) {
  color: #66b1ff;
}
</style>